//
//  FriendViewController.m
//  NewChat
//
//  Created by 马欢 on 16/2/27.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "FriendViewController.h"

#import "UIView+SDAutoLayout.h"

#import "ListTableViewCell.h"

#import "SKXChatViewController.h"
#import "MHDataHelper.h"
#import "SKXAcceptViewController.h"
#import "ConversationTableViewCell.h"
#import "SystemMessage.h"

@interface FriendViewController ()<UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate>

@property (nonatomic , strong)UISegmentedControl *typeControl;

//设置详细视图
@property (nonatomic , strong)UIScrollView * detailView;

@property (nonatomic , strong)NSMutableArray *listArray;

@property (nonatomic , strong)NSMutableArray *friendList;

@property (nonatomic , strong)NSMutableArray *converationArray;

@property (nonatomic,strong)NSMutableArray *networkArray;//存放当前登陆用户的关注的好友

@property (nonatomic , strong)NSMutableArray *friendInfoArray;

@property (nonatomic,strong)UIImageView *backgroundView;

@end

@implementation FriendViewController

//视图将要出现的时候请求数据给cell赋值
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    //添加通知中心
    //获取通知中心单例对象
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(notice:) name:systemMessageChange object:nil];

    
    
    //判断网络状态
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    //如果没网就不请求数据
    if (status == RealStatusNotReachable) {
        
    }else{
    
    
    //因为当前用户的类型是AVuser,表中key为myAttention的value中存储的也是AVuser类型的，所以不能直接使用 self.networkArray = [AVuser currentUser][@"myAttention"] 取到数组中的信息;
        [self.listArray[1] reloadData];
        
        [self.listArray[0] reloadData];

    }
    [self.listArray[1] reloadData];
    
    [self.listArray[0] reloadData];
    [self showTabbarCount];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加背景图片
    self.backgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.backgroundView.image = [UIImage imageNamed:@"find3.jpg"];
    [self.view addSubview:self.backgroundView];
    
    //  创建需要的毛玻璃特效类型
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    //  毛玻璃view 视图
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //添加到要有毛玻璃特效的控件中
    effectView.frame = self.backgroundView.bounds;
    //设置模糊透明度（范围0到1）
    effectView.alpha = 0.6f;
    [self.backgroundView addSubview:effectView];
    [self.view sendSubviewToBack:effectView];
    [self.view sendSubviewToBack:self.backgroundView];
    
    
    
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];

    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //设置列表切换
    self.typeControl = [[UISegmentedControl alloc] initWithItems:@[@"消息",@"好友",@"关注"]];
    self.typeControl.selectedSegmentIndex = 0;
    //设置导航栏头视图
    self.navigationItem.titleView = self.typeControl;
    //设置格式
    self.typeControl.sd_layout
    .heightIs(30)
    .widthIs([UIScreen mainScreen].bounds.size.width*0.5);
    
    //添加事件
    [self.typeControl addTarget:self action:@selector(changeType:) forControlEvents:(UIControlEventValueChanged)];
    
//    self.view.backgroundColor = [UIColor greenColor];
    
    //初始化detailView
    
    self.detailView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.detailView.contentSize = CGSizeMake(self.view.frame.size.width*3,1);
    self.detailView.pagingEnabled = YES;
    self.detailView.scrollEnabled = NO;
    self.detailView.showsHorizontalScrollIndicator = NO;
    self.detailView.showsVerticalScrollIndicator = NO;
    self.detailView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.detailView];
    self.detailView.sd_layout
    .topSpaceToView(self.view,0)
    .leftSpaceToView(self.view,0)
    .widthRatioToView(self.view,1)
    .heightRatioToView(self.view,1);
    
    
    //初始化listArray
    for (int i = 0 ; i<3; i++) {
        
        UITableView *temp = [[UITableView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width*i, 0, [UIScreen mainScreen].bounds.size.width, self.detailView.frame.size.height) style:(UITableViewStylePlain)];
        temp.delegate = self;
        temp.dataSource = self;
        temp.tag = 200 +i;
        temp.backgroundColor = [UIColor clearColor];
        [self.detailView addSubview:temp];
        [self.listArray addObject:temp];
        temp.sd_layout
        .topSpaceToView(self.detailView,0)
        .leftSpaceToView(self.detailView,[UIScreen mainScreen].bounds.size.width*i)
        .widthRatioToView(self.detailView,1)
        .heightRatioToView(self.detailView,1);
        
        temp.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
           
            [self reloadataListArrayWithTableView:temp];
            
        }];
    }
    //添加环信代理
    
    [self netWorkChange];

}

-(void)netWorkChange{
    
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    NSLog(@"当前网络状态%ld",status);
    
        if (status == RealStatusNotReachable) {
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                
                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            [self presentViewController:con animated:YES completion:nil];

            
        }else{
            
            [self loadConversations];
            
            [self getFriendListArray];
            
            [self.listArray[0] reloadData];
            [self.listArray[1] reloadData];
            
            AVQuery *query = [AVUser query];
            
            [query includeKey:@"myAttention"];
            
            [query whereKey:@"objectId" equalTo:[AVUser currentUser].objectId];
            
            [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                
                self.networkArray = objects.firstObject[@"myAttention"];
                
                
                [self.listArray[2] reloadData];
                
            }];
            
            
        }
    
}

-(void)reloadataListArrayWithTableView:(UITableView *)sender{
    
    RealReachability *reachability = [RealReachability sharedInstance];
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    
    NSLog(@"当前网络状态%ld",status);
    
        if (status == RealStatusNotReachable) {
            
            [sender.mj_header endRefreshing];
            
            UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                
                
            }];
            
            UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络连接" preferredStyle:(UIAlertControllerStyleAlert)];
            
            [con addAction:act];
            [self presentViewController:con animated:YES completion:nil];
            
        }else{
            
            //下拉刷新实现
            if (sender.tag == 200) {
                
                NSArray * conversations = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];

                self.converationArray = [[NSMutableArray alloc] init];

                [self.converationArray addObject:@"系统通知"];
               
                [self.converationArray addObjectsFromArray:conversations];
                
                [self.listArray[0]reloadData];
                
                [sender.mj_header endRefreshing];
                
            }else if (sender.tag == 201){
                
                [self getFriendListArray];
                
                [sender.mj_header endRefreshing];
                
            }else{
                
                AVQuery *query = [AVUser query];
                
                [query includeKey:@"myAttention"];
                
                [query whereKey:@"objectId" equalTo:[AVUser currentUser].objectId];
                
                [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    
                    self.networkArray = objects.firstObject[@"myAttention"];
                    
                    
                    [self.listArray[2] reloadData];
                    
                }];
                
                [sender.mj_header endRefreshing];
            }
            
        }
    
}

#pragma mark --- 获取会话记录 ------


-(void)loadConversations{
    
    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    
    self.converationArray = [[NSMutableArray alloc] init];
    
    if (conversations.count == 0) {
        
        conversations = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
        
        
        
        [self.converationArray addObject:@"系统消息"];
        
        [self.converationArray addObjectsFromArray:conversations];
    }else{
    
    [self.converationArray addObject:@"系统消息"];

    [self.converationArray addObjectsFromArray:conversations];
    }
    
    [self showTabbarCount];
    
}
//获取好友列表

-(void)getFriendListArray{
    
    self.friendList = nil;
    
    NSArray * array = [[EaseMob sharedInstance].chatManager buddyList];
    
    for (EMBuddy * temp in array) {
        
        
        
        if (!temp.isPendingApproval) {
            NSLog(@"好友的名字是%@",temp.username);
            
            [self.friendList addObject:temp];
            
        }
        
    }
    
    //获取好友列表
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        if (!error) {
            NSLog(@"获取成功 -- %@",buddyList);
            
            
            
            for (EMBuddy * temp in buddyList) {
                
                if (![self.friendList containsObject:temp]) {
                    
                    if (!temp.isPendingApproval) {
                        
                        [self.friendList addObject:temp];
                    }
                }
                
            }
            
            [self.listArray[1] reloadData];
            UITableView *list1 = [self.view viewWithTag:201];
            [list1.mj_header endRefreshing];
            
        }
    } onQueue:nil];
    
    [self.listArray[1] reloadData];
}

//懒加载networkArray
-(NSMutableArray *)networkArray{
    if (!_networkArray) {
        _networkArray = [NSMutableArray array];
    }
    return _networkArray;
}

//懒加载listArray
-(NSMutableArray *)listArray{
    
    if (_listArray == nil) {
        _listArray = [NSMutableArray new];
    }
    return _listArray;
}

//懒加载friendList
-(NSMutableArray *)friendList{
    
    if (_friendList == nil) {
        
        _friendList = [NSMutableArray new];
        
    }
    return _friendList;
    
}

//懒加载
-(NSMutableArray *)friendInfoArray{
    
    if (_friendInfoArray == nil) {
        _friendInfoArray = [[NSMutableArray alloc] init];
    }
    return _friendInfoArray;
    
}


//实现切换事件

-(void)changeType:(UISegmentedControl*)sender{
    
    NSLog(@"%ld",sender.selectedSegmentIndex);
    
    [self.detailView setContentOffset:CGPointMake(sender.selectedSegmentIndex*self.detailView.frame.size.width, 0) animated:YES];
}


#pragma mark -----实现tableview-----
//实现

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if([tableView isEqual:self.listArray[0]]){
        
        NSLog(@"会话的数量%ld",self.converationArray.count);
        
        return self.converationArray.count;
        
    }else if([tableView isEqual:self.listArray[1]]){
        
        
        NSLog(@"好友的数量%ld",self.friendList.count);
        
        return self.friendList.count;
        
        
    }else{
        
        return self.networkArray.count;
    }
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    
    ListTableViewCell *cell = [ListTableViewCell cellForTableView:tableView];
    ConversationTableViewCell *cell1 = [ConversationTableViewCell cellForTableView:tableView];
    
    //根据不同的内容设置cell
    if([tableView isEqual:self.listArray[0]]){
        
        if (indexPath.row==0) {
            
            cell1.usernameLabel.text = @"系统通知";
            cell1.headImageView.image = [UIImage imageNamed:@"systemBG"];
            cell1.headImageView.backgroundColor = nil;
            
            if ([SKXFriendManager sharaFriendManager].friendAcceptArray.count == 0&&[SKXFriendManager sharaFriendManager].historyAcceptArray.count == 0) {
                
                cell1.detailInfoLabel.text = @"没有新系统通知";
                cell1.asstantLabel.text = nil;
                
                cell1.asstantLabel.backgroundColor = nil;
                
            }else{
            
            if ([SKXFriendManager sharaFriendManager].friendAcceptArray.count!=0) {
                
                cell1.asstantLabel.text = [NSString stringWithFormat:@"%ld",[SKXFriendManager sharaFriendManager].friendAcceptArray.count];
                cell1.asstantLabel.backgroundColor = [UIColor redColor];
                
                SystemMessage *sys =[[SKXFriendManager sharaFriendManager].friendAcceptArray lastObject];
                cell1.detailInfoLabel.text  = sys.message;
                
                cell1.dateLabel.text = sys.timeStamp;
                
            }else{
           
            
                cell1.asstantLabel.text = nil;
                
                cell1.asstantLabel.backgroundColor = nil;
            
                SystemMessage *sys =[[SKXFriendManager sharaFriendManager].historyAcceptArray lastObject];

                cell1.dateLabel.text = sys.timeStamp;
                cell1.detailInfoLabel.text = sys.message;
            }
            }
            
        }else{
            EMConversation *temp = self.converationArray[indexPath.row];
            
            AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
            
            [userQuery includeKey:@"username"];
            
            [userQuery whereKey:@"username" equalTo:temp.chatter];
            
            [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                
                AVObject *obj = [objects lastObject];
                
                cell1.usernameLabel.text = obj[@"nickname"];
                cell1.headImageView.image = [UIImage imageNamed:obj[@"userImageName"]];
                cell1.asstantLabel.text = [NSString stringWithFormat:@"%ld",[temp unreadMessagesCount]];
                if ([temp unreadMessagesCount]!=0) {
                   cell1.asstantLabel.backgroundColor = [UIColor redColor];
                }else{
                    cell1.asstantLabel.backgroundColor = nil;
                }
                
                [cell1 setMessageCellInfoWithConversation:temp];
                
                
            }];

        }
        return cell1;
    }else if([tableView isEqual:self.listArray[1]]){
        
        EMBuddy *temp = self.friendList[indexPath.row];
        AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
        
        [userQuery includeKey:@"username"];
        
        [userQuery whereKey:@"username" equalTo:temp.username];
        
        [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            AVObject *obj = [objects lastObject];
            
            cell.userName.text = obj[@"nickname"];
            cell.dateLabel.text = obj[@"status"];
            cell.headImageView.image = [UIImage imageNamed:obj[@"userImageName"]];
            cell.detailInfoLabel.text = [NSString stringWithFormat:@"%@  %@",obj[@"gender"],obj[@"age"]];
            cell.assistLabel.text = obj[@"constellation"];
        }];
        
    }else{
        
        AVUser *user = self.networkArray[indexPath.row];
        [cell setContactCellInfoWithModel:user];
        
    }
    
    return cell;
    
}

//设置cell高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

//设置cell点击事件

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if([tableView isEqual:self.listArray[0]]){
        
        if (indexPath.row == 0) {
            
            SKXAcceptViewController * temp = [[SKXAcceptViewController alloc] init];
            
            temp.title = @"系统通知";
            
            [self.navigationController pushViewController:temp animated:YES];
            
        }else{
        
        SKXChatViewController *temp = [[SKXChatViewController alloc] init];
        
        ConversationTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            
        temp.title = cell.usernameLabel.text;
        
        EMConversation *tempCon = self.converationArray[indexPath.row];
        
        temp.chaterName = tempCon.chatter;
        
        EMBuddy *buddy = [EMBuddy buddyWithUsername:tempCon.chatter];
        
        temp.chater = buddy;
        
        temp.currentCon = tempCon;
        
        
        [self.navigationController pushViewController:temp animated:YES
         ];
        }
        
        
    }else if([tableView isEqual:self.listArray[1]]){
        
        
        SKXChatViewController *temp = [[SKXChatViewController alloc] init];
        
        ListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        temp.title = cell.userName.text;
        
        
        temp.chater = self.friendList[indexPath.row];
        
        
        [self.navigationController pushViewController:temp animated:YES
         ];
        
        
    }else{
        
        
        
        
        
    }
    
    
}


#pragma mark ------实现添加删除好友操作------



// 之前发出的好友请求被用户username拒绝了

-(void)didRejectedByBuddy:(NSString *)username{
    
    
    if ([[AVUser currentUser][@"voice"] isEqualToString:@"off"]) {
        
        
    }else{
        
        [SKXFriendManager phoneVoice];
        
    }
    
    if ([[AVUser currentUser][@"shock"] isEqualToString:@"off"]) {
        
    }else{
        
        [SKXFriendManager phoneVibrate];
    }

    
    //请求网络数据
    AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
    
    [userQuery includeKey:@"username"];
    
    [userQuery whereKey:@"username" equalTo:username];
    
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        AVObject *obj = [objects lastObject];
        
        //设置系统消息
        SystemMessage *sys = [[SystemMessage alloc] init];
        sys.accepter = obj[@"nickname"];
        //设置系统消息类型
        sys.systemMessageType = SystemMessageTypeDisagreeByFriend;
        [sys setMessageTextWithType:SystemMessageTypeDisagreeByFriend];
        [sys setAcceptTimeStamp];
        
        sys.accepterObject = obj;
        [[SKXFriendManager sharaFriendManager].friendAcceptArray addObject:sys];
        //创建一个消息对象
        NSNotification * notice = [NSNotification notificationWithName:systemMessageChange object:nil userInfo:nil];
        //发送消息
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        [self.listArray[0] reloadData];

        
    }];
   
    
}

//之前发出的好友请求被用户username接受了

- (void)didAcceptedByBuddy:(NSString *)username{
    
    
    if ([[AVUser currentUser][@"voice"] isEqualToString:@"off"]) {
        
        
    }else{
        
        [SKXFriendManager phoneVoice];
        
    }
    
    if ([[AVUser currentUser][@"shock"] isEqualToString:@"off"]) {
        
    }else{
        
        [SKXFriendManager phoneVibrate];
    }

    
    
    [self getFriendListArray];
    
    //请求网络数据
    AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
    
    [userQuery includeKey:@"username"];
    
    [userQuery whereKey:@"username" equalTo:username];
    
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        AVObject *obj = [objects lastObject];
        
        //设置系统消息
        SystemMessage *sys = [[SystemMessage alloc] init];
        sys.accepter = obj[@"nickname"];
        //设置系统消息类型
        sys.systemMessageType = SystemMessageTypeAgressByFriend;
        [sys setMessageTextWithType:SystemMessageTypeAgressByFriend];
        [sys setAcceptTimeStamp];
        
        sys.accepterObject = obj;
        [[SKXFriendManager sharaFriendManager].friendAcceptArray addObject:sys];
        //创建一个消息对象
        NSNotification * notice = [NSNotification notificationWithName:systemMessageChange object:nil userInfo:nil];
        //发送消息
        [[NSNotificationCenter defaultCenter]postNotification:notice];

        [self.listArray[0] reloadData];

    }];

    
    
}



#pragma mark ---- 接收好友的添加请求--------


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
    
}

//右划删除会话、好友
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    //根据不同的内容设置cell
    if([tableView isEqual:self.listArray[0]]){
        
        if (editingStyle == UITableViewCellEditingStyleDelete) {

        
        EMConversation * conversation = self.converationArray[indexPath.row];
        
        [[EaseMob sharedInstance].chatManager removeConversationByChatter:conversation.chatter deleteMessages:YES append2Chat:YES];
        
        [self.converationArray removeObjectAtIndex:indexPath.row];
        
            [self.listArray[0] reloadData];
            
        }
        
    }else if([tableView isEqual:self.listArray[1]]){
        
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            
            EMBuddy *temp = self.friendList[indexPath.row];
            
            EMError *error = nil;
            
            [[EaseMob sharedInstance].chatManager removeBuddy:temp.username removeFromRemote:YES error:&error];
            
            if (!error) {
                
                NSLog(@"删除好友成功");
                [self.friendList removeObjectAtIndex:indexPath.row];
                [self.listArray[1] reloadData];
                
                //请求网络数据
                AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
                
                [userQuery includeKey:@"username"];
                
                [userQuery whereKey:@"username" equalTo:temp.username];
                
                [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    
                    AVObject *obj = [objects lastObject];
                    
                    //设置系统消息
                    SystemMessage *sys = [[SystemMessage alloc] init];
                    sys.accepter = obj[@"nickname"];
                    //设置系统消息类型
                    sys.systemMessageType = SystemMessageTypeDeleteFriend;
                    [sys setMessageTextWithType:SystemMessageTypeDeleteFriend];
                    [sys setAcceptTimeStamp];
                    
                    sys.accepterObject = obj;
                    [[SKXFriendManager sharaFriendManager].friendAcceptArray addObject:sys];
                    //创建一个消息对象
                    NSNotification * notice = [NSNotification notificationWithName:systemMessageChange object:nil userInfo:nil];
                    //发送消息
                    [[NSNotificationCenter defaultCenter]postNotification:notice];

                    [self.listArray[0] reloadData];

                    
                }];

                
            }
            
        }
        
    }else{
        
    }
    
}

//监听被好友删除

-(void)didRemovedByBuddy:(NSString *)username{
    
    NSLog(@"被好友删除");
    
    
    
    if ([[AVUser currentUser][@"voice"] isEqualToString:@"off"]) {
        
        
    }else{
        
        [SKXFriendManager phoneVoice];
        
    }
    
    if ([[AVUser currentUser][@"shock"] isEqualToString:@"off"]) {
        
    }else{
        
        [SKXFriendManager phoneVibrate];
    }

    
    //accept界面实现（待定）
    [self getFriendListArray];
    
    //请求网络数据
    AVQuery *userQuery = [AVQuery queryWithClassName:@"_User"];
    
    [userQuery includeKey:@"username"];
    
    [userQuery whereKey:@"username" equalTo:username];
    
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        AVObject *obj = [objects lastObject];
        
        //设置系统消息
        SystemMessage *sys = [[SystemMessage alloc] init];
        sys.accepter = obj[@"nickname"];
        //设置系统消息类型
        sys.systemMessageType = SystemMessageTypeDeleteByFriend;
        [sys setMessageTextWithType:SystemMessageTypeDeleteByFriend];
        [sys setAcceptTimeStamp];
        
        sys.accepterObject = obj;
        [[SKXFriendManager sharaFriendManager].friendAcceptArray addObject:sys];
        //创建一个消息对象
        NSNotification * notice = [NSNotification notificationWithName:systemMessageChange object:nil userInfo:nil];
        //发送消息
        [[NSNotificationCenter defaultCenter]postNotification:notice];

        
    }];
    
}

//未读消息数改变

-(void)didUnreadMessagesCountChanged{
    
    NSLog(@"未读消息数改变");
    
    
    if ([[AVUser currentUser][@"voice"] isEqualToString:@"off"]) {
        
        
    }else{
        
        [SKXFriendManager phoneVoice];
        
    }
    
    if ([[AVUser currentUser][@"shock"] isEqualToString:@"off"]) {
        
    }else{
        
        [SKXFriendManager phoneVibrate];
    }

    
    [self.listArray[0] reloadData];
    
    [self showTabbarCount];
    
}

//历史会话记录改变

-(void)didUpdateConversationList:(NSArray *)conversationList{
    
     NSLog(@"会话列表改变");
    
    
    if (conversationList.count != 0) {
        
        self.converationArray = [NSMutableArray array];

        [self.converationArray addObject:@"系统通知"];
    
        [self.converationArray addObjectsFromArray:conversationList];
        
    }
    
    
    [self.listArray[0] reloadData];
    
    [self showTabbarCount];

    
}

-(void)showTabbarCount{
    
    NSInteger totalUnread = [SKXFriendManager sharaFriendManager].friendAcceptArray.count;
    
    for (id conversation in self.converationArray) {
        
        if ([conversation isKindOfClass:[NSString class]]) {
            
        }else{
        
        totalUnread += [conversation unreadMessagesCount];
        }
        
    }
    
    if (totalUnread!=0) {
        
        self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",totalUnread];
        
    }else{
        
        self.navigationController.tabBarItem.badgeValue = nil;
    }
    
}

-(void)notice:(id)sender{
    
    [self showTabbarCount];
    
    [self.listArray[0] reloadData];
    
}


@end
